package com.ruiyi.adrobot.web.controller.phone;/**
 * Created by tao.zeng on 2017/6/8.
 */

import com.alibaba.fastjson.JSONObject;
import com.ruiyi.adrobot.beans.NettyChannelhandlerContextMap;
import com.ruiyi.adrobot.beans.Phone;
import com.ruiyi.adrobot.beans.socket.SocketRequest;
import com.ruiyi.adrobot.beans.TaskDetail;
import com.ruiyi.adrobot.beans.common.ResultMsg;
import com.ruiyi.adrobot.mongo.phone.PhoneRepository;
import com.ruiyi.adrobot.mongo.taskdetail.TaskDetailRepository;
import com.ruiyi.adrobot.utils.LoggerUtil;
import com.ruiyi.adrobot.utils.SMSParameterUtil;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 接收第三方验证码
 *
 * @author
 * @create 2017-06-08 17:04
 **/
@Controller
@RequestMapping("/phone")
public class PhoneController {
    @Autowired
    private PhoneRepository phoneRepository;
    @Autowired
    private TaskDetailRepository taskDetailRepository;

    @RequestMapping(value = "/saveMessage", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg<Map<String, Object>> conf(HttpServletRequest request) {
        try {
            String queryStr = SMSParameterUtil.getRequestPostStr(request);
            LoggerUtil.info("接收到验证码：" + queryStr);
            Phone phone = JSONObject.parseObject(queryStr, Phone.class);
            phone.setAuthCode(getAuthCode(phone.getSms_content()));
            TaskDetail taskDetail = taskDetailRepository.findByFinishedAndFun(false, 5);
            TaskDetail.Task task;
            try {
                task = taskDetailRepository.findTaskByIdAndTasksPhone(taskDetail.getId(), phone.getPhone());
            } catch (Exception e) {
                task = taskDetailRepository.findTaskByIdAndTasksAccountInfoUserName(taskDetail.getId(), phone.getPhone());
            }
            ChannelHandlerContext ctx = NettyChannelhandlerContextMap.get(task.getExcuteSimCode());
            Map<String, Object> socketMap = new LinkedHashMap<>();
            socketMap.put("authCode", phone.getAuthCode());
            SocketRequest<Map<String, Object>> socketRequest = new SocketRequest<>("auth_code", socketMap);
            Phone newPhone = phoneRepository.findByPhone(phone.getReceiver());
            newPhone.setSms_content(queryStr);
            newPhone.setAuthCode(phone.getAuthCode());
            phoneRepository.save(newPhone);
            ctx.writeAndFlush(socketRequest.toString());
            return ResultMsg.success();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.print("");
            LoggerUtil.info(e.getMessage());
            return ResultMsg.error("服务端异常");
        }
    }

    private static String getAuthCode(String sms_content) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(sms_content);
        String authCode = m.replaceAll("").trim();
        if (authCode.length() > 6) {
            return authCode.substring(11, 17);
        } else {
            return authCode;
        }
    }

    public static void main(String[] args) {
        String a = getAuthCode("手机号13923965638的验证码为106361，请于5分钟内输入，请勿泄露。如有疑请关注微信号“飞凡逛街”联系在线客服(来自106571012010490)\n");
        System.out.print(a);
    }
}
